import { defineStore } from 'pinia';
import { authLogin, authLogout, infoUserProfile } from '@a/public';
import { moduleList, roleModuleList } from '@a/module';
import { getLightColor, getDarkColor } from '@/utils/theme/tool';
import router from '@/router';
import guarder from './guarder';

export default defineStore('user', {
	state: () => ({
		userInfo: {},
		menuTabsList: [],
		remark: '',
		token: '',
		uid: '',
		avatar: '',
		permissions: [],
		roles: [],
		elIcons: [], // 字体图标数组
		svgIcons: [], // svg字体图标数组
		theme: {
			type: 'dark',
			primaryColor: '#409eff',
			collapsible: true, //开启折叠
			showTabs: true, // 是否显示导航历史
			layout: 'sidebar', // 布局
			logo: true, // 显示logo
			menuType: 'science',
			showBreadcrumb: true // 开启面包屑
		},
		// 用户组件数据
		pageHome: false,
		packagesList: [],
		// 缓存选中菜单和tab，防止不在菜单中展示的页面刷新之后，无选中效果
		activeMenu: '',
		activeMenuTab: ''
		//
	}),
	getters: {
		columnsGets: (state) => state.columns,
		userIdGets: (state) => state.userInfo.userId,
		rolesGets: (state) => state.roles,
		permissionsGets: (state) => state.permissions
	},
	actions: {
		// 主题修改
		stateChange(data) {
			this.theme = data;
			const body = document.documentElement;
			// 设置全局顶部body上的class名称，即为主题名称，便于自定义配置符合当前主题的样式统一入口
			body.setAttribute('class', this.theme.type);
			body.setAttribute('id', this.theme.menuType);
			body.style.setProperty('--el-color-primary', this.theme.primaryColor);
			// 颜色
			for (let i = 1; i <= 9; i++) {
				body.style.setProperty(
					`--el-color-primary-light-${i}`,
					this.theme.type === 'light'
						? `${getLightColor(this.theme.primaryColor, i / 10)}`
						: `${getDarkColor(this.theme.primaryColor, i / 10)}`
				);
			}
		},
		// 登录
		Login(data) {
			return new Promise((resolve, reject) => {
				authLogin(data)
					.then((res) => {
						this.token = res?.data?.tk;
						resolve(res);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 获取用户信息
		GetInfo() {
			return new Promise((resolve, reject) => {
				infoUserProfile()
					.then((res) => {
						if (res?.data) {
							const { user, roles: Roles, perms } = res?.data || {};
							if (Roles.length) {
								// 验证返回的roles是否是一个非空数组
								this.roles = Roles;
								// 按钮级权限数组
								this.permissions = perms;
							} else {
								this.roles = ['ROLE_DEFAULT'];
							}
							this.userInfo = {
								userId: user.id,
								userName: user.userName,
								nickName: user.nickName,
								deptId: user.deptId
							};
							this.avatar = user.avatar;
							this.remark = user.remark;
							resolve(res);
						}
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 动态获取添加组件
		ModuleList(websiteId) {
			return new Promise((resolve, reject) => {
				(this.pageHome ? moduleList : roleModuleList)({ websiteId })
					.then((res) => {
						if (res?.data) {
							this.packagesList = [];
							Promise.all(
								res.data.map((item) => {
									// return import(/*@vite-ignore*/ 'http://127.0.0.1:8080/my-view-ui-basic.umd.js').then(() => {
									return import(/*@vite-ignore*/ item.umdDownloadUrl).then(() => {
										const list = [],
											data = window.RDApp[item.xvueNameSpace];
										for (const key in data) {
											if (Object.hasOwnProperty.call(data, key)) {
												const value = data[key];
												// 添加进组件选择区
												list.push({
													name: key,
													orgConfig: value.orgConfig,
													title: value.orgConfig.title
												});
												delete value.orgConfig.title;
											}
										}
										this.packagesList.push({
											key: item.xvueNameSpace,
											icon: item.icon,
											label: item.title,
											list
										});
									});
								})
							)
								.then((res) => {
									resolve(res);
								})
								.catch((error) => {
									reject(error);
								});
						}
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		// 退出系统
		LogOut() {
			return new Promise((resolve, reject) => {
				authLogout()
					.then(() => {
						this.LogOutSET();
						resolve();
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		LogOutSET() {
			// 退出登录removeRoute删除动态添加的路由
			guarder().addRouter.forEach((item) => {
				router.removeRoute(item.name || item.path);
			});
			guarder().addRouter = [];
			this.token = '';
			this.uid = '';
			this.roles = [];
			this.permissions = [];
			this.menuTabsList = [];
			this.activeMenu = '';
			this.activeMenuTab = '';
		}
	},
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				key: 'user',
				storage: localStorage,
				paths: [
					'token',
					'roles',
					'permissions',
					'userInfo',
					'avatar',
					'remark',
					'menuTabsList',
					'theme',
					'activeMenu',
					'activeMenuTab',
					'pageHome'
				]
			}
		]
	}
});
